package priv.dk.springboot.service.impl;

import org.springframework.stereotype.Service;
import priv.dk.springboot.dao.EmployeeDao;
import priv.dk.springboot.domain.entity.Employee;
import priv.dk.springboot.exception.BusinessException;
import priv.dk.springboot.service.EmployeeService;
import priv.dk.springboot.util.CommonUtil;

import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {
    private final EmployeeDao employeeDao;

    public EmployeeServiceImpl(EmployeeDao employeeDao) {
        this.employeeDao = employeeDao;
    }

    @Override
    public List<Employee> getAll() {
        return employeeDao.queryAll();
    }

    @Override
    public Employee login(Employee employee) {
        Employee emp = employeeDao.getEmpByUsername(employee.getUsername());
        // 查询是否存在该用户名
        if (emp == null) throw new BusinessException("用户名不存在");
        // 密码校验
        if (!emp.getPassword().equals(employee.getPassword()))
            throw new BusinessException("密码错误");
        // 是否是禁用账户
        if (emp.getStatus() == 0) throw new BusinessException("账户被禁用");
        return emp;
    }

    @Override
    public void addEmp(Employee employee) {
        int count = employeeDao.insert(employee);
        if (count == 0) throw new BusinessException("添加员工信息失败");
    }

    @Override
    public Employee modifyEmp(Employee employee) {
        // 执行更新
        int count = employeeDao.updateEmp(employee);
        if (count == 0) throw new BusinessException("修改员工信息失败");
        // 查询更新数据
        employee = employeeDao.queryEmpById(employee.getId());
        if (employee == null) throw new BusinessException("修改员工信息失败");
        return employee;
    }

    @Override
    public void removeEmp(Integer id) {
        int count = employeeDao.deleteEmp(id);
        if (count == 0) throw new BusinessException("删除失败");
    }

    @Override
    public void disableEmp(Integer id) {
        int count = employeeDao.updateStatus(id, CommonUtil.EMP_STATUS_DISABLE);
        if (count == 0) throw new BusinessException("禁用失败");
    }
}
